package org.engine.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Repository
public class RuleEngine {

    private static final Logger logger = LoggerFactory.getLogger(RuleEngine.class);

    private Map<String, AbstractRule> ruleCatchMap = new ConcurrentHashMap<>();

    public void addRule(String ruleId, AbstractRule rule) {
        ruleCatchMap.put(ruleId, rule);
    }

    /**
     * 风控策略执行入口
     *
     * @param ruleId            策略
     * @param ruleEngineContext 每次执行的策略缓存
     * @return
     */
    public ExecuteResult execute(String ruleId, RuleEngineContext ruleEngineContext) throws Exception {
        if (!ruleCatchMap.containsKey(ruleId)) {
            logger.error("策略不存在");
            throw new Exception("测试不存在");
        }
        AbstractRule rule = ruleCatchMap.get(ruleId);
        return rule.execute(ruleEngineContext);
    }

    public void clear() {
        this.ruleCatchMap.clear();
    }
}
